package com.yanqu.road.dao.impl.match;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.match.UserMatchData;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：zfr
 * @date ：2021/2/18 11:25
 */
public class MatchUserDataDaoImpl extends TempDataObjectDao<UserMatchData> {

    public static String addSql = "INSERT INTO t_c_variety_user_data(groupId, timeId, id, serverId, userId, patronsMap, " +
            "totalEarnSpeed, seat, userBaseInfo,dispatchTime) VALUES(?,?,?,?,?,?,?,?,?,?)";
    @Override
    protected boolean addData(UserMatchData data) {
        getDb().setConnName(DbNameStrategy.getCrossDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.BIGINT, data.getGroupId()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getTimeId()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getId()));
        para.put(i++, new DbParameter(Types.BIGINT, data.getServerId()));
        para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(data.getPatronsMap())));
        para.put(i++, new DbParameter(Types.BIGINT, data.getTotalEarnSpeed().longValue()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getSeat()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(data.getUserBaseInfo())));
        para.put(i++, new DbParameter(Types.BIGINT, data.getDispatchTime()));
        if (getDb().executeNoneQuery(addSql, para) > 0) {
            return true;
        }
        return false;
    }

    public static String updateSql = "UPDATE t_c_variety_user_data SET patronsMap = ?, totalEarnSpeed = ?, seat = ?, userBaseInfo = ?, dispatchTime = ? WHERE userId = ? and groupId = ? and timeId = ? and id = ? and serverId = ?";
    @Override
    protected boolean updateData(UserMatchData data) {
        getDb().setConnName(DbNameStrategy.getCrossDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(data.getPatronsMap())));
        para.put(i++, new DbParameter(Types.BIGINT, data.getTotalEarnSpeed().longValue()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getSeat()));
        para.put(i++, new DbParameter(Types.VARCHAR, JSON.toJSONString(data.getUserBaseInfo())));
        para.put(i++, new DbParameter(Types.BIGINT, data.getDispatchTime()));
        para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        para.put(i++, new DbParameter(Types.BIGINT, data.getGroupId()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getTimeId()));
        para.put(i++, new DbParameter(Types.INTEGER, data.getId()));
        para.put(i++, new DbParameter(Types.BIGINT, data.getServerId()));
        if (getDb().executeNoneQuery(updateSql, para) > 0) {
            return true;
        }
        return false;
    }

    @Override
    protected UserMatchData parseData(ResultSet rs) throws SQLException {
        UserMatchData data = new UserMatchData();
        data.setGroupId(rs.getLong("groupId"));
        data.setTimeId(rs.getInt("timeId"));
        data.setId(rs.getInt("id"));
        data.setServerId(rs.getLong("serverId"));
        data.setUserId(rs.getLong("userId"));
        String patronsMapStr = rs.getString("patronsMap");
        if (StringUtils.isNullOrEmpty(patronsMapStr)) {
            data.setPatronsMap(new ConcurrentHashMap<>());
        } else {
            data.setPatronsMap(JSON.parseObject(patronsMapStr, new TypeReference<ConcurrentHashMap<Integer, BigInteger>>() {}));
        }
        data.setTotalEarnSpeed(BigInteger.valueOf(rs.getLong("totalEarnSpeed")));
        data.setSeat(rs.getInt("seat"));
        String userBaseInfoStr = rs.getString("userBaseInfo");
        if (!StringUtils.isNullOrEmpty(userBaseInfoStr)) {
            data.setUserBaseInfo(JSON.parseObject(userBaseInfoStr, new TypeReference<UserBaseInfo>() {}));
        }
        data.setDispatchTime(rs.getLong("dispatchTime"));
        return data;
    }

    public static String selectSql = "SELECT * FROM t_c_variety_user_data WHERE timeId > ?";
    public Map<Long, Map<Integer, Map<Integer, List<UserMatchData>>>> getUserDataList(int timeId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, Map<Integer, Map<Integer, List<UserMatchData>>>> userDataListMap = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(selectSql);
            call.setInt(1, timeId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserMatchData data = parse(rs);
                if (!userDataListMap.containsKey(data.getGroupId())) {
                    userDataListMap.put(data.getGroupId(), new ConcurrentHashMap<>());
                }
                if (!userDataListMap.get(data.getGroupId()).containsKey(data.getTimeId())) {
                    userDataListMap.get(data.getGroupId()).put(data.getTimeId(), new ConcurrentHashMap<>());
                }
                if (!userDataListMap.get(data.getGroupId()).get(data.getTimeId()).containsKey(data.getId())) {
                    userDataListMap.get(data.getGroupId()).get(data.getTimeId()).put(data.getId(), new ArrayList<>());
                }
                userDataListMap.get(data.getGroupId()).get(data.getTimeId()).get(data.getId()).add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return userDataListMap;
    }
}
